package com.cz.nongyetongv5.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.activity.YangpinchouyangActivity.MobInterp;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.New;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.dialog.LoadingDialog;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.Conf;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.loopj.android.http.Base64;

public class WebDetailActivity extends Activity {

	/**
	 * 标题
	 */
	private TextView tvTitle = null;

	private ViewGroup btnBack = null;

	private ViewGroup btnMeanMore = null;

	private WebView wvNewsDetail = null;

	private int position = 0;

	private String newsId = null;

	private User user = null;

	public static final int TO_COMMENT = 1;

	LoadingDialog dia;

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.newdetail);

		user = (User) getIntent().getSerializableExtra("user");

		position = getIntent().getIntExtra("position", 0);

		tvTitle = (TextView) findViewById(R.id.tvTitle);

		btnBack = (ViewGroup) findViewById(R.id.btnBack);

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				doBack();
			}
		});
		View toplan=this.findViewById(R.id.toplan);
		View view = GoHomeUtil.createPopView(WebDetailActivity.this,
				new String[] { "刷新 ", "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btnRefresh = (Button) pop.getContentView()
				.findViewWithTag("btn0");

		//		final Button btnPingLun = (Button) pop.getContentView()
		//				.findViewWithTag("btn1");

		final Button btnGoHome = (Button) pop.getContentView().findViewWithTag(
				"btn1");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				}

				if (v == btnRefresh) {
					dia.dismiss();
					// blpProgress.startLoading();
					//
					// blpProgress.setVisibility(View.VISIBLE);
					wvNewsDetail.reload();

				}    else if (v == btnGoHome) {

					GoHomeUtil.goHome(WebDetailActivity.this);

				}

			}
		};

		btnRefresh.setOnClickListener(menuOnClick);


		btnGoHome.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

		String title = getIntent().getStringExtra("title");
		String type = getIntent().getStringExtra("type");
		final String pid = getIntent().getStringExtra("pid");

		if(type.equals("plan")){

			toplan.setVisibility(View.VISIBLE);
			toplan.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(WebDetailActivity.this,ChanPinJianCeActivity.class);
					// 传递到下一个页面
					intent.putExtra("user", user);
					ChanPinJianCePlanRecordActivity.pid=pid;
					startActivity(intent);
				}
			});

		}

		if(type.equals("check")){

			toplan.setVisibility(View.VISIBLE);
			toplan.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(WebDetailActivity.this,ChanPinJianCeActivity.class);
					// 传递到下一个页面
					intent.putExtra("user", user);
					ChanPinJianCePlanRecordActivity.pid=pid;
					startActivity(intent);
				}
			});

		}
		tvTitle.setText(title);

		newsId = getIntent().getStringExtra("id");


		wvNewsDetail = (WebView) findViewById(R.id.wvNewsDetail);
		wvNewsDetail.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

		// 自动加载图片
		wvNewsDetail.getSettings().setLoadsImagesAutomatically(true);
		wvNewsDetail.getSettings().setJavaScriptEnabled(true);
		wvNewsDetail.addJavascriptInterface(new MobInterp(), "mobinterp");
		wvNewsDetail.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {

				// blpProgress.stopLoading();
				//
				// blpProgress.setVisibility(View.GONE);
				dia.dismiss();

				if (wvNewsDetail.getTag() != null
						&& (Boolean) wvNewsDetail.getTag()) {

					float webViewContentHeight = wvNewsDetail
							.getContentHeight() * wvNewsDetail.getScale();

					wvNewsDetail.scrollTo(0, (int) webViewContentHeight);

					wvNewsDetail.setTag(null);

				}

			}
		});
		User user = (User) getIntent().getSerializableExtra("user");

		String url = getString(R.string.planurl);
		url+="/"+type+"Detail.html?data={\"user\":\""+user.getUsername()
				+"\",\"region\":\""+user.getKnowRegion()+"\",\""+type+"id\":\""+pid+"\"}";

		if(type.equals("check")){
			try {
				JSONObject check=new JSONObject(pid);
				url=Conf.v160918_pretask+"task.html?user="+this.getUname()+"&code="+user.getKnowRegion()+"&opt=detail&p="+check.optString("id");
				Log.d("v1609",url);
			} catch (JSONException e) { }
		}
		if(type.equals("detectDetail")){


			String param="{\"user\":\""+user.getUsername()+"\",\"detect_id\":\""+pid+"\",\"nature\":"+   getIntent().getStringExtra("n")+"}";

			url=Conf.v160918_pretask+"GetDetectDetail.html?&param="+getUrl( param);
			Log.d("v1609",url);



		}
		if(type.equals("toSamplingDetail")){
			String param="{\"user\":\""+getUname()+"\",\"sampling_id\":\""+pid+"\",\"nature\":1}";
			url=Conf.v160918_pretask+"GetSamplingDetail.html?&param="+param;
			Log.d("v1609",url);
		}


		Log.d("rafe",url);
		dia = new LoadingDialog(WebDetailActivity.this);
		dia.setCanceledOnTouchOutside(false);
		//		dia.setOnKeyListener(keylistener);
		dia.show();
		wvNewsDetail.loadUrl(url);
	}

	OnKeyListener keylistener = new DialogInterface.OnKeyListener(){
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	} ;


	@Override
	public void onBackPressed() {
		doBack();
	}

	/**
	 * 处理返回的结果
	 */
	private void doBack() {
		Intent intent = new Intent();

		intent.putExtra("position", position);

		setResult(NewListItemFragment.FORWORD_DETAIL_REQUEST_CODE, intent);

		finish();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == TO_COMMENT) {//刷新

			if (wvNewsDetail != null) {

				wvNewsDetail.setTag(true);

				dia.show();

				wvNewsDetail.reload();

			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}
	public class MobInterp{

		public MobInterp(){

		}
		@JavascriptInterface
		public void toWeb(String title,String url){
			Intent intent=new Intent(WebDetailActivity.this,WebDetail2Activity.class);

			intent.putExtra("title",title);
			intent.putExtra("url",url);
			startActivity(intent);
		}
		@JavascriptInterface
		public void toDetail(String type,String pid,String title){
			Intent intent=new Intent(WebDetailActivity.this,WebDetailActivity.class);
			intent.putExtra("pid",pid);
			intent.putExtra("type",type);
			intent.putExtra("title",title);
			intent.putExtra("user",user);
			startActivity(intent);
		}
	}
	private String getUname(){
		try {
			return URLEncoder.encode(URLEncoder.encode(user.getUsername(),"utf-8"),"utf-8");

			//  return new String(Base64.encode(user.getUsername().getBytes("utf-8"),Base64.DEFAULT));
		} catch ( Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user.getUsername();
	}
	private String getUrl(String data){
		try {
			return URLEncoder.encode(URLEncoder.encode(data,"utf-8"),"utf-8");

			//  return new String(Base64.encode(user.getUsername().getBytes("utf-8"),Base64.DEFAULT));
		} catch ( Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user.getUsername();
	}

}


